import {
	resPost,
} from "../common/http.request";
import {
	uniLinkTo,
} from "../utils/uniPromise";
import {
	getStockMaxAndMinNum
} from "../module/product/prodMet";
const iconArr = {
	index: {
		icon: 'e63d',
		actIcon: 'e63c',
	},
	category: {
		icon: 'e742',
		actIcon: 'e742',
	},
	cart: {
		icon: 'e73d',
		actIcon: 'e73c',
	},
	user: {
		icon: 'e66e',
		actIcon: 'e66e',
	},
}

/**
 * 加载底部tabbar
 * @param commit
 * @param state
 * @returns {Promise<unknown>}
 */
export const loadTabBarList = ({
	commit,
	state
}) => {
	return new Promise(((resolve, reject) => {
		resPost('GetCommonPicList', {
			type: 14
		}).then(({
			data
		}) => {
			let tabBar = data.length === 0 ? state.vuex_tab_bar_default : data.reduce((
				resultObj, item) => {
				let url = ''
				let query = {}
				let arr1 = []
				let obj = {}
				if (item.mini_url) {
					arr1 = item.mini_url.split('?')
					url = arr1[0]
					if(arr1[1]){
						let arr2 = arr1[1].split('&')
						arr2.forEach((routeItem) => {
							let newArr = routeItem.split('=')
							query[newArr[0]] = newArr[1]
						})
					}
					obj = iconArr[arr1[0]] || {}
				}
				resultObj.list.push({
					query: query,
					iconPath: state.vuex_config.videoSwiper ? '' : (item.img ||
						obj.icon),
					selectedIconPath: state.vuex_config.videoSwiper ? '' : (item
						.side_pic || obj.actIcon),
					text: item.name,
					url: url
				})
				return resultObj
			}, {
				list: [],
				activeColor: state.vuex_config.themeColor1,
				inactiveColor: '#666666',
				current: state.vuex_tab_bar.current
			})
			tabBar.activeColor = state.vuex_config.themeColor1
			tabBar.inactiveColor = '#666666'
			tabBar.current = state.vuex_tab_bar.current || 0
			commit('$uStore', {
				name: 'vuex_tab_bar',
				value: tabBar
			})
			// commit('checkCurrentTab')
			resolve(data)
		}).catch(() => {
			reject('获取tabbar失败')
		})
	}))
}

/**
 * 获取openid
 * @param commit
 * @param state
 * @param params
 * @returns {Promise<unknown>}
 */
export const loadUserOpenid = ({
	commit,
	state
}, params = {}) => {
	return new Promise(((resolve, reject) => {
		params = {
			superior: state.vuex_superior,
			appid: state.vuex_business.appid,
			secret: state.vuex_business.secret,
			...params
		}
		resPost('GetUserOpenid', params).then(({
			data
		}) => {
			if (data.pk_id) {
				commit('$uStore', {
					name: 'vuex_token',
					value: data.pk_id
				})
				resolve()
			} else {
				reject('获取openid失败')
			}
		}).catch(() => {
			reject('获取openid失败')
		})
	}))
}
/**
 * 获取商家信息
 * @param commit
 * @param state
 * @returns {Promise<unknown>}
 */
export const loadBusinessInfo = ({
	commit,
	state
}) => {
	return new Promise((resolve, reject) => {
		resPost('GetBusinessInfo', {
			business_id: undefined,
			appid: state.vuex_businessObj.appid
		}).then(({
			data
		}) => {
			console.log('商家信息加载结束')
			if (data.pk_id) {
				commit('$uStore', {
					name: 'vuex_business',
					value: data
				})
				let arr = Object.keys(state.vuex_config)
				let vuex_config = {
					...state.vuex_config
				}
				arr.forEach((key)=>{
					if(data[key] || data[key] === 0){
						vuex_config[key] = data[key]
					}
				})
				vuex_config.themeColor1 = data.theme_color || vuex_config.themeColor1
				// #ifdef APP-PLUS
				vuex_config.union_pay = 0
				// #endif
				// #ifndef APP-PLUS
				vuex_config.account_login = 0
				// #endif
				commit('$uStore', {
					name: 'vuex_config',
					value: vuex_config
				})
				resolve(data)
			} else {
				commit('$uStore', {
					name: 'vuex_business',
					value: {
						pk_id: state.vuex_business.pk_id
					}
				})
				reject(data)
			}
		}).catch(err => {
			reject(err)
		})
	})
}
/**
 * 获取保存用户信息，加载购物车列表
 * @param commit
 * @param state
 * @param params {} // 用户信息，没传就查一次
 * @returns {Promise<unknown>}
 */
export const loadUserInfo = ({
	commit,
	state
}, params) => {
	return new Promise(((resolve, reject) => {
		if (params && params.pk_id) {
			// commit('$uStore', {
			// 	name: 'vuex_user',
			// 	value: params
			// })
			commit('$uStore', {
				name: 'vuex_token',
				value: params.pk_id
			})
			loadUserCartList({
				commit
			})
			wx.onCopyUrl(()=>{
				return {query:'isShareLinkUrl=1'}
			})
			resolve(params)
		}
		
			let obj = {}
			if (params && params.dev) {
				obj.users_id = params.users_id
			}
			resPost('GetUsersInfo', obj).then(({
				data
			}) => {
				if (data.pk_id) {
					commit('$uStore', {
						name: 'vuex_user',
						value: data
					})
					commit('$uStore', {
						name: 'vuex_token',
						value: data.pk_id
					})
					loadUserCartList({
						commit
					}) // 又不需要显示购物车数量，干嘛一开始加载
					wx.onCopyUrl(()=>{
						return {query:'isShareLinkUrl=1'}
					})
					resolve(data)
				} else {
					commit('$uStore', {
						name: 'vuex_user',
						value: {
							pk_id: ''
						}
					})
					commit('$uStore', {
						name: 'vuex_token',
						value: ''
					})
					reject({
						pk_id: ''
					})
				}
			}).catch((err) => {
				commit('$uStore', {
					name: 'vuex_user',
					value: {
						pk_id: ''
					}
				})
				commit('$uStore', {
					name: 'vuex_token',
					value: ''
				})
				// #ifdef H5
				// uniLinkTo('/package/common/auth/index', 'redirectTo')
				// #endif
				reject(err)
			})
	}))
}

/**
 * 获取用户余额、积分、收藏的值
 * @param commit
 * @returns {Promise<unknown>}
 */
export const loadUserCount = ({
	commit
}) => {
	return new Promise(((resolve, reject) => {
		resPost('GetUsersCount').then(({
			data
		}) => {
			commit('$uStore', {
				name: 'vuex_count',
				value: data
			})
			resolve(data)
		}).catch(() => {
			reject('未获取到用户余额')
		})
	}))
}

/**
 * 检查分销商id
 * @param commit
 * @param state
 */
export function checkIsUpdateSuperior({
	commit,
	state
}, newSuperior) {
	return new Promise((resolve, reject) => {
		if (newSuperior && newSuperior != '0') {
			if (state.vuex_token) {
				if (state.vuex_business.lock_powder == 1 && newSuperior != state.vuex_token) {
					resPost('UpdateUsersAgent', {
						superior: newSuperior
					}).then(() => {
					})
					commit('$uStore', {
						name: 'vuex_superior',
						value: '0'
					})
				} else {
					commit('$uStore', {
						name: 'vuex_superior',
						value: '0'
					})
					reject()
				}
			} else {
				commit('$uStore', {
					name: 'vuex_superior',
					value: newSuperior
				})
			}
		} else {
			commit('$uStore', {
				name: 'vuex_superior',
				value: '0'
			})
		}
	})
}

/**
 * 获取用户购物车信息
 * @param commit
 * @returns {Promise<unknown>}
 */
export const loadUserCartList = ({
	commit
}) => {
	return new Promise((resolve, reject) => {
		resPost('GetMallShoppingCartList').then(({
			data
		}) => {
			data.forEach(item => {
				item.max_num = item.max_num ? parseInt(item.max_num) : 10
				item.stock_num = item.stock_num ? parseInt(item.stock_num) : 10
				item.min_num = item.min_num ? parseInt(item.min_num) : 0
				item.num = item.num ? parseInt(item.num) : 0
				item.purchase_quantity = item.purchase_quantity ? parseInt(item
					.purchase_quantity) : 0
				item = getStockMaxAndMinNum(item, true)
				item.num = item.num <= item.max_num ? item.num : item.max_num
				item.price = (item.r_price || item.r_price === 0)?item.r_price : item.price
				item.rebate = (item.r_rebate || item.r_rebate === 0)?item.r_rebate : item.rebate
			})
			commit('$uStore', {
				name: 'vuex_cart_list',
				value: data
			})
			commit('$uStore', {
				name: 'vuex_cart_num',
				value: data.reduce((sum, item) => sum + item.num, 0)
			})
			resolve(data)
		}).catch((err) => {
			reject(err)
		})
	})
}

/**
 * 添加产品到购物车
 * @param commit
 * @param params
 * @returns {Promise<unknown>}
 */
export const addProdToCart = ({
	commit
}, params) => {
	return new Promise((resolve, reject) => {
		resPost('AddMallShoppingCart', params).then(() => {
			loadUserCartList({
				commit
			}).then(() => {
				resolve()
			}).catch(() => {
				resolve()
			})
		}).catch(() => {
			reject()
		})
	})
}
/**
 * 获取系统信息
 * 	微信小程序：计算自定义导航栏内容高度
 * 为什么要写这个：因为有些页面我要做定位的时候，需要知道top应该是多少
 * */
export const getSystemData = ({
	dispatch,
	commit,
	state
}) => {
	let wxSystem = uni.getSystemInfoSync()
	state.vuex_system = {
		...wxSystem
	}
	// #ifndef H5 || APP-PLUS
		// #ifdef MP-WEIXIN
		dispatch('meixinHeader')
		// #endif
		// #ifndef MP-WEIXIN
		state.vuex_system.contH = 44
		state.vuex_system.top = wxSystem.statusBarHeight + 44
		// #endif
	// #endif
}

// #ifdef MP-WEIXIN
export const meixinHeader = ({
	dispatch,
	commit,
	state
}) => {
	// 有些ios手机这个api的环境加载慢可能会导致拿不到数据：getMenuButtonBoundingClientRect
	let capsule = uni.getMenuButtonBoundingClientRect()
	if (capsule.height > 0) {
		// 导航栏内容高度 = 状态栏到胶囊的间距（胶囊距上边界距离-状态栏高度） * 2 + 胶囊高度
		let contH = capsule.height + (capsule.top - state.vuex_system.statusBarHeight) * 2
		if (state.vuex_system.system.includes('iPhone') || state.vuex_system.system.includes('iOS')) {
			// ios感觉都矮了些
			contH = contH + 2
		}
		state.vuex_system.contH = contH
		state.vuex_system.top = state.vuex_system.statusBarHeight + contH
	} else {
		setTimeout(()=>{
			dispatch('meixinHeader')
		},300)
	}
}
// #endif
